package cc.laop.support.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.ShiroException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class ExceptionHandler implements HandlerExceptionResolver {

	private static final Logger logger = LoggerFactory
			.getLogger(ExceptionHandler.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object obj, Exception exception) {
		String requestType = request.getHeader("X-Requested-With");
		logger.error("Error! requestType : {}", requestType);
		logger.error(exception.getMessage(), exception);
		if ("XMLHttpRequest".equals(requestType)) {
			write(response, exception);
		} else {
			ModelAndView mv = new ModelAndView();
			if (exception instanceof ShiroException) {
				mv.setViewName("/error/noPermission");
			} else {
				mv.setViewName("/error/error");
			}
			mv.addObject("message", exception.getMessage());
			return mv;
		}
		return null;
	}

	public void write(HttpServletResponse response, Exception exception) {
		PrintWriter out = null;
		try {
			out = response.getWriter();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("result", -1);
			map.put("message", exception.getMessage());
			ObjectMapper mapper = new ObjectMapper();
			String result = mapper.writeValueAsString(map);
			out.append(result);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

}
